import { format, getSign, getUserInfor } from "./component/untils.js"

export default class Client {
    constructor(uid, opts) {
        this.uid = uid;
        this.opts = opts;
        this.hasLogin = false;
        this.IMclient = null;

        this.query = null;

        this.imaTaiKai = null;
        this.conversations = {};
        this.conversationsList = [];
        this.login();
    }
    login() {
        let self = this;
        getSign().then((signatureFactory) => {
            return realtime.createIMClient(this.uid, { signatureFactory })
                .then(function (c) {
                    console.log(`登录成功`)
                    self.IMclient = c;
                    self.hasLogin = true;
                    self.init();
                })
        })
            .catch(this.opts.failCallback)
    }

    init() {
        this.query = this.IMclient.getQuery();
        this.getAllConversation();
        this.initEvent();
    }
    //初始化事件
    initEvent() {
        let c = this.IMclient;
        let self = this;
        //收到邀请事件
        c.on(AV.Event.INVITED, (payload, e) => {
            //如果当前会话已经存在就不再添加了
            if (this.conversations[e.id]) {
                return;
            }
            else {
                this.addConversation(e);
            }
            self.opts.whenInvited && self.opts.whenInvited(payload, e);
        });
        //收到消息事件
        c.on(AV.Event.MESSAGE, function (message, conversation) {
            doMessageTime(message)
            conversation.History.push(message);
            conversation.waitNum += 1;
            if (self.imaTaiKai === conversation) {
                conversation.read();
            }
            self.opts.whenMessage && self.opts.whenMessage(...arguments);
        });
    }
    //增加新的会话
    addConversation(e) {
        e.History = [];
        e.messageIterator = null;
        e.waitNum = 0;
        this.conversationsList.push(e);
        this.conversations[e.id] = e;
    }
    //获取当前用户所有会话
    getAllConversation() {
        let self = this;
        this.query.find().
            then(function (conversations) {
                conversations.map((v) => {
                    self.addConversation(v);
                })
                self.opts.whenInited && self.opts.whenInited(self);
            })
            .catch(console.error.bind(console));
    }
    //进入某个对话
    changeConversation(id) {
        if (!id) {
            this.imaTaiKai = null;
        }
        else {
            this.imaTaiKai = this.conversations[id] || null;
        }
    }
    //向对话内发送消息
    sendMessage(msg, callback) {
        if (this.imaTaiKai) {
            msg = new AV.TextMessage(msg)
            this.imaTaiKai.send(msg).then((msg) => {
                this.imaTaiKai.History.push(doMessageTime(msg));
                callback && callback(msg);
            });
        }
        else {
            console.log("尚未进入任何一个聊天室");
        }
    }
    //获取当前对话的聊天历史记录 默认十条
    getHistory(callback, num = 10) {
        let c = this.imaTaiKai;
        if (c) {
            if (!c.messageIterator) {
                c.messageIterator = c.createMessagesIterator({ limit: num });
            }
            c.messageIterator.next()
                .then((v) => {
                    for (let i = 0; i < v.value.length; i++) {
                        let m = v.value[i];
                        doMessageTime(m);
                    }
                    c.HistoryHasDone = v.done;
                    if (v.value.length === 0 && v.History && v.History.length === 0) {
                        v.value.splice(0, 0, { isTimeLine: true, time: "快和新朋友打个招呼吧" })
                    }
                    else if (!v.done) {
                        v.value.splice(0, 0, { isTimeLine: true, time: format(v.value[0]._timestamp, "yyyy年MM月dd日") })
                    }
                    c.History = v.value.concat(c.History);
                    callback(v);
                })
                .catch(console.error.bind(console));
        }
    }
    //创建新的会话
    createNewConversation(numberList, callback) {
        this.IMclient.createConversation({
            members: [numberList],
            name: this.uid + " & " + numberList,
            unique: true
        }).then((e) => {
            if (this.conversations[e.id]) {
                console.log("已存在会话")
            }
            else {
                this.addConversation(e);
                e.send(new AV.TextMessage("你好，我是" + (userInfor[this.uid] && userInfor[this.uid].username) || "用户" + this.uid))
            }
            callback(e)
        });
    }
}
function doMessageTime(m) {
    let msg = m._lctext;
    let reg = /[w\.\\]*jiandanmaimai\.cn\/file\/(\d+)/
    if (reg.test(msg)) {
        m.hasfile = {
            id: msg.match(reg)[1],
        }
    }
    m._time = m._timestamp.toString().substr(16, 5);
    return m;
}